package com.h5;

import java.util.Collection;
import java.util.Date;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.demo.annotation.LoginFilter;
import com.demo.annotation.MobileMethod;
import com.demo.mobile.MobileInfo;
import com.demo.util.JSONUtils;
import com.demo.util.ProperityUtil;
import com.demo.validator.MobileLoginValidate;
import com.shopcart.domain.CreditCategory;
import com.vsd.domain.ChangeLog;
import com.vsd.domain.CreditGoods;
import com.vsd.domain.User;
import com.vsd.domain.UserCreditLog;
import com.vsd.repository.ChangeLogRepository;
import com.vsd.repository.CreditGoodsRepository;
import com.vsd.repository.UserCreditLogRepository;
import com.vsd.repository.UserRepository;
import com.vsd.service.ChangeLogService;
import com.vsd.service.CreditCategoryService;
import com.vsd.service.CreditGoodsService;
import com.vsd.service.UserCreditLogService;
import com.vsd.service.UserService;
import com.zy.credit.proto.MOCredit.MCreditGoods;
import com.zy.credit.proto.MOCredit.MCreditGoodsList;

@Controller
@RequestMapping("/m/credit")
public class H5CreditController extends H5BaseController {

	@Autowired
	private UserService userService;
	@Autowired
	private UserCreditLogService userCreditLogService;
	@Autowired
	private CreditCategoryService creditCategoryService;
	@Autowired
	private CreditGoodsService creditGoodsService;
	@Autowired
	JdbcTemplate jdbcTemplate;
	@Autowired
	private CreditGoodsRepository creditGoodsRepository;
	@Autowired
	private UserRepository userRepository;
	@Autowired
	private UserCreditLogRepository userCreditLogRepository;
	@Autowired
	private ChangeLogRepository changeLogRepository;
	@Autowired
	private ChangeLogService changeLogService;
	@Autowired
	private ProperityUtil properityUtil;
	
	@RequestMapping("/credit")
	@ResponseBody
	public String myCredit(HttpSession session) {
		String userId = getSessionParameter(session, "id");
		User user = userService.findByPrimaryKey(userId);
		return JSONUtils.serialize(user);
	}
	
	@RequestMapping("/detail")
	@ResponseBody
	public String detail(String id){
		CreditGoods goods = creditGoodsService.findOne(id);
//		goods.setContent(properityUtil.getSelf_url()+"detail?id="+id+"&type=3");
		return JSONUtils.serialize(goods);
	}

	@RequestMapping("/log")
	@ResponseBody
	@LoginFilter(outpage = "/m/login")
	public String log(HttpSession session, Integer page, Integer limit) {
		String userId = getSessionParameter(session, "id");
		Page<UserCreditLog> list = userCreditLogService.findByUserId(userId,
				new PageRequest(page, limit, new Sort(Direction.DESC,
						"createTime")));
		return JSONUtils.serialize(list);
	}

	@RequestMapping("/cate")
	@ResponseBody
	public String cate() {
		Collection<CreditCategory> list = creditCategoryService
				.findAllByOrderBySortDesc();
		return JSONUtils.serialize(list);
	}

	@RequestMapping("/goods")
	@ResponseBody
	public String goods(String code, Integer page, Integer limit) {
		Page<CreditGoods> list = null;
		if (StringUtils.isBlank(code)) {
			list = creditGoodsService.findAll(new PageRequest(page, limit,
					new Sort(Direction.DESC, "createTime")));
		} else {
			list = creditGoodsService.findByCateCode(code, new PageRequest(
					page, limit, new Sort(Direction.DESC, "createTime")));
		}
		return JSONUtils.serialize(list);
	}

	@RequestMapping("/exchange")
	@ResponseBody
	@LoginFilter(outpage = "/m/login")
	public String exchange(HttpSession session, String id) {
		String userId = getSessionParameter(session, "id");
		if (StringUtils.isBlank(userId)){
			return JSONUtils.serialize(new Ret(-2,"未登录"));
		}
		CreditGoods goods = creditGoodsService.findOne(id);
		Ret ret = new Ret();
		ret.setCode(1);
		if (goods == null) {
			ret.setCode(0);
			ret.setData("商品不存在");
			return JSONUtils.serialize(ret);
		}
		if (goods.getTotal() <= 0) {
			ret.setCode(0);
			ret.setData("商品已经兑换完");
			return JSONUtils.serialize(ret);
		}

		User u = userService.findByPrimaryKey(userId);
		if (u.getCredit() < goods.getNum()) {
			ret.setCode(-1);
			ret.setData("积分不足");
			return JSONUtils.serialize(ret);
		}
		// 扣除积分
		String sql = "update f_user u set u.credit = u.credit-"
				+ goods.getNum() + " where u.id=" + userId
				+ " and u.credit >= " + goods.getNum();
		int count = jdbcTemplate.update(sql);
		if (count > 0) {
			// 保存积分日志
			UserCreditLog log = new UserCreditLog();
			log.setCreateTime(new Date());
			log.setFid(goods.getId());
			log.setInfo("兑换积分商品：" + goods.getTitle());
			log.setItem("兑换积分商品：" + goods.getTitle());
			log.setNum(goods.getNum());
			log.setTotal(u.getCredit()); // 更新前数量
			log.setType(2);
			log.setUserId(userId);
			userCreditLogRepository.save(log);
			// 更新积分商品库存
			sql = "update s_credit_goods g set g.total = g.total - 1 where g.id = "
					+ id;
			jdbcTemplate.equals(sql);
			// 生成兑奖记录
			ChangeLog cLog = new ChangeLog();
			cLog.setCreateTime(new Date());
			cLog.setFid(id);
			cLog.setState(1);
			cLog.setType(1);
			cLog.setUserId(userId);
			changeLogRepository.save(cLog);
		}
		return JSONUtils.serialize(ret);
	}
	
	/**
	@api mMyCreditGoods mMyCreditGoods	//我的礼品
	@return MCreditGoodsList 
	*/
	@RequestMapping("/myCreditGoods")
	public String mMyCreditGoods(HttpSession session,Integer page,Integer limit) throws Exception {
		String userId = getSessionParameter(session, "id");
		MCreditGoodsList.Builder result = changeLogService.findByUserId(userId, page, limit);
		JSONArray ret = new JSONArray();
		for (MCreditGoods.Builder mini : result.getListBuilderList()){
			JSONObject m = new JSONObject();
			m.put("content", mini.getContent());
			m.put("credit", mini.getCredit());
			m.put("id", mini.getId());
			m.put("img", mini.getImg());
			m.put("imgs", mini.getImgs());
			m.put("info", mini.getInfo());
			m.put("name", mini.getName());
			m.put("state", mini.getState());
			ret.add(m);
		}
		return JSONUtils.serialize(ret);
	}
}
